package com.zgf.easy.proxy.mgr;

import com.zgf.easy.proxy.mgr.info.ImplInfo;
import com.zgf.easy.proxy.mgr.info.ModuleInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @project: easy_proxy
 * @author: zgf1
 * @date: 2021/12/26 14:23
 */
@Slf4j
public class ObjectMgr {

    private final static Map<String, Map<Class<?>, ImplInfo>> identityImplMap = new ConcurrentHashMap<>();
    private final static Map<String, ModuleInfo> identityModuleMap = new ConcurrentHashMap<>();

    /**
     * 注册模块映射关系
     * @param identity
     * @param moduleInfo
     */
    public static void register(String identity, ModuleInfo moduleInfo) {

        log.info("注册module identity={}, moduleInfo={}", identity, moduleInfo);
        identityModuleMap.put(identity, moduleInfo);
    }

    /**
     * 注册映射关系
     * @param identity
     * @param interfaceClass
     * @param implInfo
     */
    public static void register(String identity, Class<?> interfaceClass, ImplInfo implInfo) {
        log.info("注册ipml identity={}, interfaceClass={}, implInfo={}", identity, interfaceClass, implInfo);
        Map<Class<?>, ImplInfo> implMap = identityImplMap.get(identity);
        if (implMap == null) {
            implMap = new ConcurrentHashMap<>();
            identityImplMap.put(identity, implMap);
        }
        implMap.put(interfaceClass, implInfo);
    }

    /**
     * 获取映射关系对象
     * @param identity
     * @param interfaceClass
     */
    public static Object get(String identity, Class<?> interfaceClass) {
        return get(identity, interfaceClass, true);
    }

    /**
     * 获取映射关系对象
     * @param identity
     * @param interfaceClass
     * @param overrideQry 是否依赖查找
     */
    public static Object get(String identity, Class<?> interfaceClass, boolean overrideQry) {
        if (StringUtils.isEmpty(identity)) {
            return null;
        }
        ModuleInfo moduleInfo = identityModuleMap.get(identity);
        if (moduleInfo == null) {
            throw new IllegalArgumentException("身份" + identity + "非法");
        }
        Map<Class<?>, ImplInfo> implMap = identityImplMap.get(identity);
        if (implMap == null) {
            return get(moduleInfo.getAutoModule().parentIdentity(), interfaceClass, false);
        }
        ImplInfo info = implMap.get(interfaceClass);
        if (info == null) {
            return get(moduleInfo.getAutoModule().parentIdentity(), interfaceClass, false);
        }
        if (!overrideQry || StringUtils.isEmpty(info.getAutoService().overrideIdentity())) {
            return info.getObj();
        }
        Object obj = get(info.getAutoService().overrideIdentity(), interfaceClass, false);
        if (obj != null) {
            return obj;
        }
        return info.getObj();
    }

}
